jQuery(function() {

  var $ = jQuery;
  var menu = findProductsMenu();

  if (menu) {
    fetchProductCategories(function(categories) {
      console.log(categories);
      addProductsToMenu(categories, menu);

      $('.qin-product-category').each(function() {
        var el = $(this);
        var slug = el.attr('id');

        var list = getCategoriesBySlug(categories, slug);

        var html = _.map(list.childs, function(it) {
          return ['<li><a href="/product-category/', it.slug ,'">', it.name.replace(/\s*mobile\s*/i, '') ,'</a></li>'].join('');
        }).join('');

        el.append(html);
      });
    });
  }

  function fetchProductCategories(callback) {
    jQuery.ajax({
      url: '/wp-json/qin/v1/products/categories',
      dataType: 'json',
      success: function(data) {
        callback(getProductCategories(data));
      }
    });
  }


  function addProductsToMenu(categories, menu) {
    if (!categories || categories.length === 0)  { return ; }

    menu.addClass('menu-item-has-children');

    var html = ['<ul class="product-sub-menu product-category-menu">', _.map(categories, productCatToHtml).join(''), '</ul>'].join('');

    menu.append(html);
  }

  function productCatToHtml(cat) {
    var hasChild = cat.level < 2 && cat.childs && cat.childs.length > 0;
    var childs = '';

    if (hasChild) {
      var isMega = '';

      if (cat.childs.length > 13) {
        isMega = ' mega-menu';
      }

      if (cat.childs.length > 26) {
        isMega += ' mega-menu-3x';
      }

      childs = ['<ul class="product-sub-menu', isMega ,'">', _.map(cat.childs, productCatToHtml).join(''), '</ul>'].join('');
    }

    return ['<li id="menu-item-', cat.id, '" class="menu-item menu-item-type-taxonomy menu-item-object-product_cat menu-item-', cat.id,' ', (hasChild ? 'menu-item-has-children' : ''), '">',
    '<a href="', location.origin, '/product-category/', cat.slug,'/">', cat.name, '</a>', childs,
    '</li>'].join('');
  }

  function findProductsMenu() {
    var menus = jQuery('#menu-header').children();

    var target = _.filter(menus, function(it) {
      var menu = jQuery(it).find('a:first');

      return /\/products\/$/.test(menu.attr('href'));
    });

    return target ? jQuery(target) : null;
  }

  function getProductCategories(data) {
    var map = {};

    _.each(data, function(it) {
      map[it.id] = it;
    });

    _.each(data, function(it) {
      if (it.parent) {
        var parent = map[it.parent];

        if (parent) {
          parent.childs = parent.childs || [];

          parent.childs.push(it);
        }
      }
    });

    var list = _.filter(data, function(it) { return it.parent === 0; });

    return addLevel(list, 1);
  }

  function addLevel(list, lv) {
    _.each(list, function(it) {
      it.level = lv;

      if (it.childs) {
        addLevel(it.childs, lv + 1);
      }
    });

    return list;
  }

  function getCategoriesBySlug(categories, slug) {
    return _.find(categories, function(it) { return it.slug === slug; });
  }

});
